package com.cn.lf.wx.dacs.bussiness.author.action;

import java.util.Objects;

import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.cn.lf.wx.dacs.bussiness.author.bean.BaseException;
import com.cn.lf.wx.dacs.bussiness.author.bean.ReturnEntity;
import com.cn.lf.wx.dacs.bussiness.author.utils.Code;
import com.cn.ym.log.Log;

@RestControllerAdvice
public class RestExceptionHandler {

    /**
     * 统一处理自定义基础异常
     */
    @ExceptionHandler({BaseException.class})
    public ReturnEntity baseException(BaseException e) {
        if (Objects.isNull(e.getCode())) {
            return ReturnEntity.FAILED(e.getMessage());
        }
        return ReturnEntity.FAILED(e.getCode(), e.getMessage());
    }


    @ExceptionHandler({DataAccessException.class})
    public ReturnEntity dataAccessException(DataAccessException e) {
        Log.error("数据库错误, {}"+e.getMessage());
        return ReturnEntity.FAILED(Code.DATA_ACCESS_EXCEPTION_MESSAGE, Code.Msg.DATA_ACCESS_EXCEPTION_MESSAGE);
    }

    @ExceptionHandler({HttpMessageNotReadableException.class})
    public ReturnEntity bodyMissException() {
        return ReturnEntity.FAILED(Code.NOT_FOUND_BODY, Code.Msg.NOT_FOUND_BODY);
    }

    @ExceptionHandler({AccessDeniedException.class})
    public ReturnEntity accessDeniedException() {
        return ReturnEntity.FAILED(Code.NOT_ACCESS, Code.Msg.NOT_ACCESS);
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ReturnEntity httpRequestMethodNotSupportedException() {
        return ReturnEntity.FAILED(Code.NOT_METHOD_SUPPORTED, Code.Msg.NOT_METHOD_SUPPORTED);
    }

    /**
     * 默认全局异常处理。
     *
     * @param e the e`
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ReturnEntity exception(Exception e) {
        Log.error("全局异常信息 ex={}"+ e.getMessage());
        e.printStackTrace();
        return ReturnEntity.FAILED(Code.NOT_LOGIN, Code.Msg.BASE_SYS_ERROR);
    }
}
